package com.example.auth.config;

import com.example.auth.filter.JwtAuthenticationFilter;
import com.example.auth.handler.CustomAccessDeniedHandler;
import com.example.auth.handler.CustomAuthenticationEntryPointHandler;
import com.example.auth.handler.CustomAuthenticationFailureHandler;
import com.example.auth.service.CustomUserDetailsService;
import com.example.common.constant.ServiceConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * the spring security config
 *
 * @author cui haida
 * @version JDK 8
 * 2025/8/4
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * a bean
     * the custom user details service
     * this service is used to load the user, loadUserByUsername
     */
    @Resource
    private CustomUserDetailsService customUserDetailsService;

    /**
     * a bean
     * the jwt authentication filter
     * this filter will be used to validate the token
     * the filter is before the username password authentication filter
     */
    @Resource
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    /**
     * a bean
     * the custom authentication failure handler
     */
    @Resource
    private CustomAuthenticationFailureHandler authenticationFailureHandler;

    /**
     * a bean
     * the custom access denied handler
     */
    @Resource
    private CustomAccessDeniedHandler accessDeniedHandler;

    /**
     * a bean
     * the custom authentication entry point handler
     */
    @Resource
    private CustomAuthenticationEntryPointHandler authenticationEntryPointHandler;

    /**
     * the configure of authentication
     * the param is the auth manager builder
     * will use the custom user details service and password encoder
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * password encoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * authentication manager bean
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * the configure for web security
     * - will disable csrf and use stateless session
     * - will add the jwt authentication filter before the username password authentication filter
     * - will pass when the request is authenticated(login and register)
     * - will add the custom access denied handler and custom authentication entry point handleradd the custom access denied handler and custom authentication entry point handler
     * - will add the white list
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // disable csrf and session
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // the configure for auth
        // set the route of permit all(login and register), other routes need auth
        // add the jwt authentication filter before the username password authentication filter
        http.authorizeRequests()// 请求授权
                .antMatchers("/auth/login", "/auth/register").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); // 添加JWT过滤器

        // the configure for form login
        // set the login page
        // add the custom access denied handler and custom authentication entry point handler
        // set the white list
        http.formLogin()
                .loginPage(ServiceConstants.WHITE_LIST[0])
                .failureHandler(authenticationFailureHandler)
                .and()
                .authorizeRequests()
                .antMatchers(ServiceConstants.WHITE_LIST).permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(authenticationEntryPointHandler);
    }
}